package com.xyf.sys.service.impl;

import cn.hutool.core.date.DateUtil;
import com.xyf.sys.config.CustomException;
import com.xyf.sys.domain.Goods;
import com.xyf.sys.domain.RegimentAssist;
import com.xyf.sys.domain.Role;
import com.xyf.sys.domain.User;
import com.xyf.sys.mapper.GoodsMapper;
import com.xyf.sys.service.*;
import com.xyf.sys.vo.GoodsListParam;
import com.xyf.sys.vo.OrderUserResult;
import com.xyf.sys.vo.SaleCountResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author R-H
 * @Date 2024/8/311112
 * @Description
 */
@Service
@Slf4j
public class IGoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IOrderProductService orderProductService;

    @Override
    public void add(Goods goods) {
        User user = userService.get(goods.getUserId());
        List<Role> roleList = userRoleService.getRoleList(user.getId());
        if (!roleList.stream().filter(role -> "MERCHANT".equalsIgnoreCase(role.getRoleKey()) || "GROUPLEADER".equalsIgnoreCase(role.getRoleKey())).findAny().isPresent()){
            throw new CustomException("无权限");
        }
        if (goods.getDeptId() == null){
            goods.setDeptId(user.getDeptId());
        }
        if (goods.getId() == null){
            goods.setStatus((byte)1);
            this.insert(goods);
        } else {
            this.update(goods);
        }
    }

    @Override
    public int insert(Goods goods) {
        goods.setDelFlag("0");
        goods.setCreateBy(goods.getUserId());
        goods.setCreateTime(new Date());
        goods.setLastUpdateTime(new Date());
        goods.setSort(countGoods() == null ? 1 : countGoods() + 1);
        return goodsMapper.insert(goods);
    }

    @Override
    public int update(Goods goods) {
        goods.setUpdateBy(goods.getUserId());
        goods.setUpdateTime(new Date());
        goods.setLastUpdateTime(new Date());
        return goodsMapper.updateByPrimaryKeySelective(goods);
    }

    @Override
    public Integer countGoods() {
        return goodsMapper.count();
    }

    @Override
    public List<Goods> getList(GoodsListParam body) {
        List<Goods> list = goodsMapper.selectList(body);
        List<Long> goodsIds = list.stream().map(Goods::getId).collect(Collectors.toList());
        List<SaleCountResult> results = orderProductService.countSaleAndTotalStock(goodsIds, DateUtil.today());
        Map<Long, SaleCountResult> resultMap = results.stream().collect(Collectors.toMap(SaleCountResult::getProductId, result -> result));
        List<OrderUserResult> goodsUsers = orderProductService.findGoodsUsers(goodsIds);
        Map<Long, List<User>> userMap = goodsUsers.stream().collect(Collectors.toMap(OrderUserResult::getProductId, OrderUserResult::getUsers, (v1, v2) -> v1));
        for (Goods goods : list) {
            SaleCountResult result = resultMap.getOrDefault(goods.getId(), new SaleCountResult(goods.getId(), 0, 0));
            goods.setSaleStock(result.getSaleCount());
            goods.setTotalSaleStock(result.getTotalSaleCount());
            goods.setOrderUser(userMap.getOrDefault(goods.getId(), Collections.emptyList()));
        }
        return list;
    }

    @Override
    public Goods get(Long id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public Goods getInfo(Long id) {
        Goods goods = this.get(id);
        List<Long> goodsIds = Arrays.asList(goods.getId());
        List<SaleCountResult> results = orderProductService.countSaleAndTotalStock(goodsIds, DateUtil.today());
        Map<Long, SaleCountResult> resultMap = results.stream().collect(Collectors.toMap(SaleCountResult::getProductId, result -> result));
        List<OrderUserResult> goodsUsers = orderProductService.findGoodsUsers(goodsIds);
        Map<Long, List<User>> userMap =  goodsUsers.stream().collect(Collectors.toMap(OrderUserResult::getProductId, OrderUserResult::getUsers, (v1, v2) -> v1));
        SaleCountResult result = resultMap.getOrDefault(goods.getId(), new SaleCountResult(goods.getId(), 0, 0));
        goods.setSaleStock(result.getSaleCount());
        goods.setTotalSaleStock(result.getTotalSaleCount());
        goods.setOrderUser(userMap.getOrDefault(goods.getId(), Collections.emptyList()));
        return goods;
    }
    @Override
    public Object remove(Long id, String userId) {
        Goods goods = this.get(id);
        goods.setDelFlag("1");
        goods.setUpdateBy(userId);
        return this.update(goods);
    }

    @Override
    public Object downGoods(Long id, String userId) {
        Goods goods = this.get(id);
        goods.setStatus((byte)-1);
        goods.setUpdateBy(userId);
        return this.update(goods);
    }

    @Override
    public Object upGoods(Long id, String userId) {
        Goods goods = this.get(id);
        goods.setStatus((byte)1);
        goods.setUpdateBy(userId);
        return this.update(goods);
    }

    @Override
    public List<User> queryCommunityGroupBuyingList(Long queryDeptId) {
        return goodsMapper.queryCommunityGroupBuyingUserList(queryDeptId, DateUtil.today());
    }

    @Override
    public Object updateStock(Goods body) {
        Goods goods = this.get(body.getId());
        goods.setStock(body.getStock());
        goods.setUpdateBy(body.getUserId());
        return this.update(goods);
    }

    @Override
    public List<Goods> queryGoodsByDeptId(Long deptId) {
        return goodsMapper.selectByDeptId(deptId);
    }

    @Override
    public List<Goods> getList(Long[] ids) {
        List<Goods> list = goodsMapper.selectByIds(ids);
        List<Long> goodsIds = list.stream().map(Goods::getId).collect(Collectors.toList());
        List<SaleCountResult> results = orderProductService.countSaleAndTotalStock(goodsIds, DateUtil.today());
        Map<Long, SaleCountResult> resultMap = results.stream().collect(Collectors.toMap(SaleCountResult::getProductId, result -> result));
        List<OrderUserResult> goodsUsers = orderProductService.findGoodsUsers(goodsIds);
        Map<Long, List<User>> userMap = goodsUsers.stream().collect(Collectors.toMap(OrderUserResult::getProductId, OrderUserResult::getUsers, (v1, v2) -> v1));
        for (Goods goods : list) {
            SaleCountResult result = resultMap.getOrDefault(goods.getId(), new SaleCountResult(goods.getId(), 0, 0));
            goods.setSaleStock(result.getSaleCount());
            goods.setTotalSaleStock(result.getTotalSaleCount());
            goods.setOrderUser(userMap.getOrDefault(goods.getId(), Collections.emptyList()));
        }
        return list;
    }
}
